package com.weiweiqin.controller.home;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.weiweiqin.model.*;
import com.weiweiqin.service.*;
import com.weiweiqin.utils.BigDemicalUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.config.AlipayConfig;
import com.alipay.util.AlipaySubmit;
import com.weiweiqin.constants.Constants;
import com.weiweiqin.vo.common.CartVO;
import com.weiweiqin.vo.common.OrderQueryVO;
import com.weiweiqin.vo.common.OrderTabVO;
import com.weiweiqin.vo.common.Page;
import com.weiweiqin.vo.common.Result;

@Controller
@RequestMapping("front/order")
public class FOrderController {
	private static final Logger logger = LoggerFactory
			.getLogger(FOrderController.class);
	@Autowired
	private OrderService orderService;

	private static String getHeader(HttpServletRequest request, String headName) {
        String value = request.getHeader(headName);
        return !StringUtils.isBlank(value) && !"unknown".equalsIgnoreCase(value) ? value : "";
    }

	@RequestMapping(value = "/add.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String add(Order order,HttpServletRequest request,
					  HttpSession session) {
		logger.info("Enter method add....，order=" + order);
		Result result = new Result();
		String ipFromNginx = getHeader(request, "X-Real-IP");
		String ip = StringUtils.isEmpty(ipFromNginx) ? request.getRemoteAddr() : ipFromNginx;
		logger.info("ip=" + ip);
		// 保存订单信息
		try {
			//设置用户IP
			order.setIp(ip);
			order.setStatus(0);
			orderService.save(order);
		} catch (Exception e) {
			logger.error("保存订单失败...", e);
			result.setResult(false);
			result.setErrorMsg("系统繁忙，请您稍后再试！");
			return result.toJson();
		}
		result.setResult(true);
		result.setObj(order);
		return result.toJson();
	}

	@RequestMapping(value = "/updateBC.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String updateBC(Order order,HttpServletRequest request,
					  HttpSession session) {
		logger.info("Enter method updateBC....，order=" + order);
		Result result = new Result();
		String ipFromNginx = getHeader(request, "X-Real-IP");
		String ip = StringUtils.isEmpty(ipFromNginx) ? request.getRemoteAddr() : ipFromNginx;
		logger.info("ip=" + ip);
		// 保存订单信息
		try {
			//设置用户IP
			order.setIp(ip);
			order.setStatus(0);
			orderService.update(order);
		} catch (Exception e) {
			logger.error("补充图片失败...", e);
			result.setResult(false);
			result.setErrorMsg("系统繁忙，请您稍后再试！");
			return result.toJson();
		}
		result.setResult(true);
		result.setObj(order);
		return result.toJson();
	}

	@RequestMapping(value = "/pageList.do", method = {RequestMethod.GET })
	@ResponseBody
	public String pageListForCustomer(OrderQueryVO orderVO, HttpSession session) {
		logger.info("Enter pageList ...,orderVO=" + orderVO+"customerId="+orderVO.getCustomerId());
		Result result = new Result();
		Page page = new Page();
		page.setPageSize(100);
		page.setCurrPage(orderVO.getCurrPage());
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("customerId", orderVO.getCustomerId());
		if (null != orderVO.getStatus()) {
			conditions.put("status", orderVO.getStatus());
		}
		if (!StringUtils.isEmpty(orderVO.getTitle())) {
			conditions.put("title", orderVO.getTitle().trim());
		}

		if (!StringUtils.isEmpty(orderVO.getName())) {
			conditions.put("name", orderVO.getName().trim());
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		List<Order> orderList = orderService.pageList(page, conditions);
		List<OrderTabVO> orderVOList = new ArrayList<OrderTabVO>();
		if (null != orderList) {
			for (Order order : orderList) {
				OrderTabVO vo = new OrderTabVO();
				vo.setOrder(order);
				Date updateDate = order.getUpdateDate();
				String format = sdf.format(updateDate);
				vo.setUpdateDate(format);
				orderVOList.add(vo);
			}
		}
		int totalCount = orderService.totalCount(conditions);
		Map<String, Object> mp = new HashMap<String, Object>();
		mp.put("totalPage", page.getTotalPage());
		mp.put("totalCount", totalCount);
		mp.put("list", orderVOList);
		result.setObj(mp);
		result.setResult(true);
		return result.toJson();
	}

	@RequestMapping(value = "/orderSuccess/{outerid}", method = {
			RequestMethod.POST, RequestMethod.GET })
	public String orderSuccess(@PathVariable String outerid, String trade_no,
			String trade_status, HttpServletRequest request) {
		request.setAttribute("outerid", outerid);
		Order order = orderService.getByOuterid(outerid);
		if (null != order) {
			order.setTradeNo(trade_no);
			order.setTradeStatus(trade_status);
			orderService.update(order);
		}
		return "orderSuccess";
	}
	
	@RequestMapping(value = "/porderSuccess/{outerid}", method = {
			RequestMethod.POST, RequestMethod.GET })
	public String porderSuccess(@PathVariable String outerid, String trade_no,
			String trade_status, HttpServletRequest request) {
		request.setAttribute("outerid", outerid);
		Order order = orderService.getByOuterid(outerid);
		if (null != order) {
			order.setTradeNo(trade_no);
			order.setTradeStatus(trade_status);
			orderService.update(order);
		}
		return "pc/porderSuccess";
	}

	@RequestMapping(value = "/get.do", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public String get(int id) {
		Result result = new Result();
		Order order = null;
		try {
			order = orderService.get(id);
		} catch (Exception e) {
			logger.error("数据库异常...",e);
			result.setErrorMsg("数据库异常...");
			result.setResult(false);
			return result.toJson();
		}
		Map<String,Object> data = new HashMap<String, Object>();
		data.put("order",order);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			String format = sdf.format(order.getUpdateDate());
			data.put("date", format);
		} catch (Exception e) {
			logger.error("格式化时间错误,",e);
		}
		result.setObj(data);
		result.setResult(true);
		return result.toJson();
	}

	@RequestMapping(value = "/getByOuterid.do", method = {RequestMethod.GET })
	@ResponseBody
	public String getByOuterid(String outerid) {
		Result result = new Result();
		Order order = null;
		try {
			order = orderService.getByOuterid(outerid);
		} catch (Exception e) {
			logger.error("数据库异常...",e);
			result.setErrorMsg("数据库异常...");
			result.setResult(false);
			return result.toJson();
		}
		result.setObj(order);
		result.setResult(true);
		return result.toJson();
	}
}